package com.example.reagent_management.ui.operatedialog.viewmodle

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.paging.filter
import com.example.reagent_management.room.entity.ReagentInformation
import com.example.reagent_management.ui.operatedialog.repository.ReagentRepository
import com.kunminx.architecture.ui.callback.UnPeekLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class ReagentManagerViewModel @Inject constructor(private val reagentRepository: ReagentRepository) :
    ViewModel() {

    val reagentMessages = UnPeekLiveData<PagingData<ReagentInformation>>()

    //过滤结果
    fun getAllReagent(filter: String) : Job{
       return viewModelScope.launch {
            reagentRepository.getAll().flow.cachedIn(viewModelScope)
                .flowOn(Dispatchers.Default)
                .collectLatest {
                    delay(100)
                    if (filter.isNotEmpty()){
                       val data =  it.filter { its ->
                            its.projectName.contains(filter) || its.reagentName.contains(filter) || its.reagentType.contains(filter)
                        }
                        reagentMessages.postValue(data)
                    }else{
                        reagentMessages.postValue(it)
                    }
                }
        }
    }
}
